//
//  SpectailDetail.swift
//  甜言蜜语
//
//  Created by yingli_yanfa_liuxingyu on 16/8/18.
//  Copyright © 2016年 wl. All rights reserved.
//

import UIKit
import SVProgressHUD
class SpectailDetail: UIViewController, SpectailDetailHeaderCellDelegate, UIWebViewDelegate{
    @IBOutlet weak var tableView: UITableView!
    
    var id:String = ""
    var modelList: specialDetailInfo?{
        didSet{
            self.tableView.reloadData()
            self.initRightItem()
            self.loadNewsDetail()
            
        }
    }
    var isshoucang: Bool?
    var msg: regiestInfo?
    var cellHeight = 0
    var webView: UIWebView!
    override func viewDidLoad() {
        super.viewDidLoad()
        self.title = "品牌主页"
        publicMethod.setHUDStyle()
        let cellNib = UINib(nibName: "SpectailDetailHeaderCell", bundle: nil)
        self.tableView.registerNib(cellNib, forCellReuseIdentifier: "SpectailDetailHeaderCell")
        
        
        self.webView = UIWebView(frame: CGRect(x: 0, y: 0, width: SCREEN_WIDTH, height: 1))
        self.webView.delegate = self
        self.webView.scrollView.scrollEnabled = false
        
        NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(SpectailDetail.tableViewReload(_:)), name:"webCellHeight_Noti", object: nil)
        
      self.getSpectailDetailInfo(id)
       
    }
    override func viewWillAppear(animated: Bool) {
        super.viewWillAppear(animated)
        self.tabBarController?.tabBar.hidden = true
    }
    override func viewWillDisappear(animated: Bool) {
        SVProgressHUD.dismiss()
        super.viewWillDisappear(animated)
    }
    //移除通知
    deinit {
        
        NSNotificationCenter.defaultCenter().removeObserver(self, name: "webCellHeight_Noti", object: nil)
        
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    func initRightItem(){
        let img: UIImage?
        if self.modelList?.isshoucang == true{
             img = UIImage(named: "collection_selected")
        }else{
             img = UIImage(named: "collection-white")
        }
        //收藏
        let collectionBtn = UIButton(frame: CGRectMake(0, 0, 20, 20))
        //collectionBtn.setBackgroundImage(img, forState: UIControlState.Normal)
        collectionBtn.setImage(img, forState: UIControlState.Normal)
        collectionBtn.addTarget(self, action: #selector(self.collectionAction), forControlEvents:  UIControlEvents.TouchUpInside)
        let collection = UIBarButtonItem(customView: collectionBtn)
        //转发
        let ForwardBtn = UIButton(frame: CGRectMake(0, 0, 20, 20))
        //ForwardBtn.setBackgroundImage(UIImage(named: "share-1"), forState: UIControlState.Normal)
        ForwardBtn.setImage(UIImage(named: "share-1-white"), forState: UIControlState.Normal)
        ForwardBtn.addTarget(self, action: #selector(self.ForwardAction), forControlEvents:  UIControlEvents.TouchUpInside)
        let Forward = UIBarButtonItem(customView: ForwardBtn)
        
        //举报
        let ReportBtn = UIButton(frame: CGRectMake(0, 0, 20, 20))
        ReportBtn.setBackgroundImage(
            UIImage(named: "Report-white"), forState: UIControlState.Normal)
        //ReportBtn.setImage(UIImage(named: "Report"), forState: UIControlState.Normal)
        ReportBtn.addTarget(self, action: #selector(self.ReportAction), forControlEvents:  UIControlEvents.TouchUpInside)
        let Report = UIBarButtonItem(customView: ReportBtn)
        
        self.navigationItem.rightBarButtonItems = [collection, Forward,Report]
        

        
    }
    func collectionAction(){
        if ApplicationDelegate.isLogin(){
            self.getSpecitalCollection()
        }else{
            let sb = UIStoryboard(name: "Login", bundle: nil)
            let vc = sb.instantiateViewControllerWithIdentifier("LoginViewController")
            self.navigationController?.pushViewController(vc, animated: true)
        }
        
    }
    func ForwardAction(){
        let shareParames = NSMutableDictionary()
        let url = String(format: "%@zycp/fenxiang/\(id)",BaseUrl)
        
        shareParames.SSDKSetupShareParamsByText("",
                                                images : UIImage(named: "ShareImg.png"),
                                                url : NSURL(string:url),
                                                title : "专业产品",
                                                type : SSDKContentType.Auto)
        
        
        //2.进行分享
        SSUIShareActionSheetStyle.setShareActionSheetStyle(ShareActionSheetStyle.Simple)
        
        ShareSDK.showShareActionSheet(self.view, items: nil  , shareParams: shareParames) { (state : SSDKResponseState, platformType : SSDKPlatformType, userdata : [NSObject : AnyObject]!, contentEnity : SSDKContentEntity!, error : NSError!, end) -> Void in
            
            switch state{
                
            case SSDKResponseState.Success: print("分享成功")
            case SSDKResponseState.Fail:    print("分享失败,错误描述:\(error)")
            case SSDKResponseState.Cancel:  print("分享取消")
                
            default:
                break
            }
        }
    }
    func ReportAction(){
        self.reportBtnClicked()
    }
    //MARK:SpectailDetailHeaderCellDelegate
    func companyCallBtnClicked(text: String){
         publicMethod.callPhone(text, withSuperView: self.view)
        
    }
    func agentCallBtnClicked(text: String){
         publicMethod.callPhone(text, withSuperView: self.view)
    }
    //MARK:noti
    func tableViewReload(notification:NSNotification){
        
       
        let height = notification.object!.valueForKey("height") as! CGFloat
        self.cellHeight = Int(height)
        self.tableView.reloadData()
        
    }

    //MARK:tableviewDataSource
    func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        return 2
    }
    func tableView(tableView: UITableView,heightForHeaderInSection section: Int) -> CGFloat{
        if section == 0{
            return 0
        }else{
            return 50
        }
        
        
    }
    
   func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
        if(cell.respondsToSelector(Selector("setSeparatorInset:"))) {
            cell.separatorInset = UIEdgeInsetsMake(0, 0, 0, 0)
        }
        if(cell.respondsToSelector(Selector("setLayoutMargins:"))) {
            cell.layoutMargins = UIEdgeInsetsMake(0, 0, 0, 0)
        }
    }
    
    
    func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        if section == 0{
            return view
        }else{
            let sectionView = UIView()
            let label=UILabel(frame:CGRectMake(10,10, 50, 40))
            label.text="相关新闻"
            label.font = UIFont.systemFontOfSize(11)
            label.textColor = UIColor.lightGrayColor()
            sectionView .addSubview(label)
            return sectionView
        }
    }
    
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if section == 0{
            if self.modelList == nil{
                return 0
            }else{
                return 1
            }
        }else{
            if self.modelList?.infomations?.count != 0 && self.modelList?.infomations?.count != nil{
                return (self.modelList?.infomations?.count)!
            }else{
                return 0
            }
            
        }
        
    }
    func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        if indexPath.section == 0{
            var cellHeight: CGFloat = 0.0
            if self.modelList?.showtype == "cs"{
                cellHeight += 148
               
            }else if self.modelList?.showtype == "dl"{
                cellHeight += 148
               
            }else{
                cellHeight += 296
            }
            cellHeight += self.webView.frame.size.height
            cellHeight += 242
            
            return cellHeight

            
        }else{
            let newsModel =  self.modelList?.infomations![indexPath.row]
            return newsModel!.cellType!.cellHeight()
        }
        
    }
    
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        if indexPath.section == 0{
            let cell = tableView.dequeueReusableCellWithIdentifier("SpectailDetailHeaderCell") as! SpectailDetailHeaderCell
            cell.delegate = self
            let cellInfo = self.modelList
            cell.tureWebView.addSubview(self.webView)
            cell.selectionStyle = UITableViewCellSelectionStyle.None
            cell.setCellContentWithCellInfo(cellInfo)
            return cell
        }else{
            let model = self.modelList?.infomations![indexPath.row]
            
            let cell = tableView.dequeueReusableCellWithIdentifier(model!.cellType.rawValue, forIndexPath: indexPath) as! NewsCell
            
            cell.newsModel = model
            
            return cell

        }
    }
    
    func scrollViewDidScroll(scrollView: UIScrollView) {
        let sectionHeaderHeight: CGFloat = 0
        if scrollView.contentOffset.y <= sectionHeaderHeight && scrollView.contentOffset.y >= 0 {
            scrollView.contentInset = UIEdgeInsetsMake(-scrollView.contentOffset.y, 0, 0, 0)
        }
        else if scrollView.contentOffset.y >= sectionHeaderHeight {
            scrollView.contentInset = UIEdgeInsetsMake(-sectionHeaderHeight, 0, 0, 0)
        }
        
    }
    
    // MARK: - Table view delegate
    func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        
        tableView.deselectRowAtIndexPath(indexPath, animated: true)
        if indexPath.section == 0{
            
        }else{
            if self.modelList?.infomations![indexPath.row].type == 4{
                //特殊新闻
                let sb = UIStoryboard(name: "NewsList", bundle: nil)
                let vc = sb.instantiateViewControllerWithIdentifier("SpecialNewsController") as! SpecialNewsController
                vc.newsModel = self.modelList?.infomations![indexPath.row]
                self.navigationController?.pushViewController(vc, animated: true)
            }else if self.modelList?.infomations![indexPath.row].type == 5{
                //视频新闻
                let sb = UIStoryboard(name: "NewsList", bundle: nil)
                let vc = sb.instantiateViewControllerWithIdentifier("DetaillNewsController") as! DetaillNewsController
                vc.newsModel = self.modelList?.infomations![indexPath.row]
                self.navigationController?.pushViewController(vc, animated: true)
                
            }else if self.modelList?.infomations![indexPath.row].type == 6{
                //直播新闻
                let sb = UIStoryboard(name: "NewsList", bundle: nil)
                let vc = sb.instantiateViewControllerWithIdentifier("DetaillNewsController") as! DetaillNewsController
                vc.newsModel = self.modelList?.infomations![indexPath.row]
                self.navigationController?.pushViewController(vc, animated: true)
            }else if self.modelList?.infomations![indexPath.row].type == 8{
                //淘宝新闻
                let sb = UIStoryboard(name: "NewsList", bundle: nil)
                let vc = sb.instantiateViewControllerWithIdentifier("DetaillNewsController") as! DetaillNewsController
                vc.newsModel = self.modelList?.infomations![indexPath.row]
                self.navigationController?.pushViewController(vc, animated: true)
            }else{
                //正常新闻
                let sb = UIStoryboard(name: "NewsList", bundle: nil)
                let vc = sb.instantiateViewControllerWithIdentifier("DetaillNewsController") as! DetaillNewsController
                vc.newsModel = self.modelList?.infomations![indexPath.row]
                self.navigationController?.pushViewController(vc, animated: true)
            }

        }
        
        
    }
    //MARK:target
    //举报
    func reportBtnClicked(){
        let vc = self.storyboard?.instantiateViewControllerWithIdentifier("ReportVC") as! ReportVC
        vc.id = self.modelList!.id
        self.navigationController?.pushViewController(vc, animated: true)
    }
    
    //MARK:NETWORKING
    func getSpectailDetailInfo(id:String){
        DataTool.specialDetail(id,completionHandler: { (newModel) in
            guard let newDataes = newModel else {
                return
            }
            print(newDataes)
            self.modelList = newDataes
           
            
        })

    }
    //收藏专业产品
    func getSpecitalCollection(){
        if self.modelList?.isshoucang == true{
            self.isshoucang = false
        }else{
            self.isshoucang = true
        }
        let urlStr = String(format: "%@brand/shoucang",BaseUrl)
        DataTool.specialProductCollection((self.modelList?.id)!,url: urlStr , isshoucang: self.isshoucang!,completionHandler: { (newModel) in
            guard newModel != nil else {
                return
            }
            self.msg = newModel
            self.getSpectailDetailInfo((self.modelList?.id)!)
           
            SVProgressHUD.showSuccessWithStatus(self.msg?.msg)
        })

    }
    
    /**
     加载描述界面
     */
    func loadNewsDetail() {
        
        assert(self.modelList != nil)
        let css = NSBundle.mainBundle().URLForResource("Details.css", withExtension: nil)!
        
        var html = "<html>"
        
        html += "<head>"
        html += "<link rel=\"stylesheet\" href="
        html += "\"\(css)\""
        html += ">"
        html += "</head>"
        
        html += self.getBody()
        html += "</html>"
        
        self.webView.loadHTMLString(html, baseURL: nil)
        
    }
    /**
     被loadNewsDetail方法调用，用来拼接<body>的内容
     */
    func getBody() -> String{
        var body = "<body style='font-size: 20)px'>"
        
        body += "<div class=\"title\" style='font-size: 20)px'>"
        
        body += self.modelList!.title
        body += "</div>"
        
        
        body += "<div class=\"time\">"
        body += self.modelList!.ptime
        body += "</div>"
        
        body += self.modelList!.body
        
        for (index, detailImageModel) in self.modelList!.brandimgs!.enumerate() {
            var imgTag = "<div class=\"image\">"
            
            imgTag += "<img id=\"\(index)\" "
            //用 * 符号切割字符串，"haha*hehe*xixi" ==>  "haha" "hehe" "xixi"
            let pixel = detailImageModel.pixel.componentsSeparatedByString("*")
            var width = Float(pixel.first!) ?? 0
            var height = Float(pixel.last!) ?? 0
            
            let maxWidth = Float(SCREEN_WIDTH * 0.95)
            if width > maxWidth {
                height =  height *  maxWidth / width
                width = maxWidth
            }
            
            // 这里是添加图片点击事件
            imgTag += "onload="
            imgTag += "\""
            imgTag += "this.onclick = function() {  window.location.href = 'sx:index=' +this.id;};"
            imgTag += "\""
            
            imgTag += "width=\(width) "
            imgTag += "height=\(height) "
            imgTag += "src=\(detailImageModel.src)>"
            
            imgTag += "<div class=\"imageDetail\">"
            imgTag += "\(detailImageModel.alt)"
            imgTag += "</div>"
            
            
            imgTag += "</div>"
            
            // 替换位置
            body = body.stringByReplacingOccurrencesOfString(detailImageModel.ref, withString: imgTag)
        }
        
        body += "</body>"
        
        return body
    }
    //MARK: webViewDelegate
    func webViewDidFinishLoad(webView: UIWebView) {
        
        let webHeightStr = webView.stringByEvaluatingJavaScriptFromString("document.body.scrollHeight")
        
        let webHeight:CGFloat = CGFloat((webHeightStr! as NSString).floatValue)
        
        self.webView.frame = CGRect(x: self.webView.frame.origin.x, y: self.webView.frame.origin.y, width: SCREEN_WIDTH, height: webHeight)
        
        self.tableView.reloadData()
    }
    


}
